package com.amt.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;


/**
 * @Title: ExportUtil
 * @Package: com.amt.util
 * @Description: TODO(导出文档工具类)
 * @Author: 杜强
 * @Date: 2020年04月07日 16:26
 * Copyright (c) ©1994-2019 Scjydz.com All Rights Reserved.
 **/
@Component
public class ExportUtil<T> {
    /**
     * 导出Excel
     *
     * @param title    标题
     * @param headers  表格列名
     * @param data     数据(仅限实体类，并且列名的顺序要和实体类中的属性方法顺序一致)
     * @param response 输出流
     * @param pattern  如果有时间数据，设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     */
    public void exportExcel(String title, String[] headers, Collection<T> data, HttpServletResponse response, String pattern) throws Exception {
        OutputStream out = response.getOutputStream();
        if (StringUtil.isEmpty(pattern)) {
            pattern = "yyyy-MM-dd hh:mm:ss";
        }
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_50_PERCENT.getIndex());
//        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
//        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontName("宋体");
        font.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        font.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
//        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
//        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
//        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
//        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        HSSFCell cellHeader;
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
        }
        // 遍历集合数据，产生数据行
        Iterator<T> it = data.iterator();
        int index = 0;
        T t;   //定义接收实体
        HSSFCell cell;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            t = it.next();
            //使用反射获取实体类方法,动态调用方法获取值
            Field[] fieldList = t.getClass().getDeclaredFields();
            for (int i = 0; i < fieldList.length; i++) {
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                //获取get方法
                PropertyDescriptor descriptor = new PropertyDescriptor(fieldList[i].getName(), t.getClass());
                Method method = descriptor.getReadMethod();
                Object value = method.invoke(t);
                if (value != null) {
                    if (fieldList[i].getType().getSimpleName().equals("Date")) {
                        cell.setCellValue(DateUtil.format((Date) value, pattern));
                        continue;
                    } else if (fieldList[i].getType().getSimpleName().equals("BigDecimal")) {
                        BigDecimal money = (BigDecimal) value;
                        cell.setCellValue(money.toString());
                        continue;
                    }
                    cell.setCellValue(String.valueOf(value));
                    continue;
                }
                cell.setCellValue("");
            }
        }
        response.setContentType("application/octet-stream");
        response.setHeader("filetype", "xls");
        response.setHeader("Content-disposition", "attachment;filename=" + title + ".xls");// 默认Excel名称
        response.flushBuffer();
        workbook.write(out);
        out.close();
    }
}
